package multithreading;


import java.util.concurrent.*;

/**
 * @Filename: ImplementationThread
 * @Author: czh
 * @Data:2023/7/11 10:24
 * 实现线程的四种方式
 * 继承Thread
 * 实现Runnable
 * 实现Callable
 * 实现线程池
 */
public class ImplementationThread {
    public static void main(String[] args) {
        //  继承Thread
        MyThread myThread = new MyThread();
        myThread.start();
        //  实现Runnable
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();
        //  实现Callable
        MyCallable myCallable = new MyCallable();

        // 模拟多线程分步操作
        String[] str = new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};

        // 线程池 使用runnable 模拟多线程分别打印数组中得每一个字符
        ThreadPoolExecutor executor = ThreadPool.getExecutor();
        try {
            for (String s : str) {
                executor.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + ": " + s);
                });
            }
        } finally {
            executor.shutdown();
        }
        // 线程池 使用callable 模拟多线程分别打印数组中得每一个字符
        try {
            for (String s : str) {
                Future<String> future = executor.submit(() -> {
                    System.out.println(Thread.currentThread().getName() + ": " + s);
                    return s;
                });
                String s1 = future.get();
                System.out.println("=====" + s1);
            }
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            executor.shutdown();
        }
    }
}

class MyThread extends Thread {
    @Override
    public void run() {
        // ...
    }
}

class MyRunnable implements Runnable {

    @Override
    public void run() {

    }
}

class MyCallable implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        return null;
    }
}


// 定义一个线程池 静态内部类方式
class ThreadPool {
    // 定义一个线程池
    private static final ThreadPoolExecutor threadPoolExecutor;

    static {
        threadPoolExecutor = new ThreadPoolExecutor(9, 20, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
    }

    private ThreadPool() {
    }

    public static ThreadPoolExecutor getExecutor() {
        return threadPoolExecutor;
    }
}